package com.wulis.config.security;

import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static com.wulis.common.constant.GlobalConstant.BEARER;
import static com.wulis.common.constant.GlobalConstant.TOKEN_PREFIX;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.wulis.common.utils.JwtTokenUtil;
import com.wulis.config.swagger.SwaggerSecurityConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * @author WuliBao
 */
@Slf4j
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {
    
    @Resource
    private SwaggerSecurityConfig swaggerSecurityConfig;
    
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        String authHeader = request.getHeader(AUTHORIZATION);
        if (authHeader != null && authHeader.startsWith(BEARER)) {
            final String authToken = authHeader.substring(BEARER.length());
            AuthUserDetails authUserDetails = JwtTokenUtil.parseToken(authToken);
            if (authUserDetails != null) {
                // 判断redis中token是否存在
                String token = redisTemplate.opsForValue().get(TOKEN_PREFIX + authUserDetails.getAccountId());
                if (token != null && token.equals(authToken)
                    && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        authUserDetails, null, authUserDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        // 执行swagger账号filter策略
        swaggerSecurityConfig.doFilterInternal(authHeader, request);
        chain.doFilter(request, response);
    }
}
